package test.designmode.masterworker;

import java.util.Queue;

/**
 * Created by linshuo on 2018/3/4.
 *
 * Master-worker模式: 计算 2^0 + 2^1 + 2^2 + 2^3 + 2^4 + ... + 2^9
 *
 * 1. Master是公共可复用的, PowerWorker与PowerArgs是耦合的与业务相关的
 * 2. Worker就是线程, run里面while中从jobQueue取任务, 做完将结果往resultQueue里面丢
 * 3. Master维护了jobQueue resultQueue workerQueue, 控制着workerQueue任务的添加与开工
 */
public class Main {
    public static void main(String[] args) {
        PowerWorker worker = new PowerWorker();
        Master master = new Master(worker, 5);
        for (int i = 0; i < 10; i++) {
            PowerArgs powerArgs = new PowerArgs();
            powerArgs.setBase(2);
            powerArgs.setIndex(i);
            master.addJob(powerArgs);
        }
        master.start();
        /* 不断轮询结果队列, 提前处理结果, 而不用等所有结果出来再处理 */
        Queue<Object> results = master.getResultQueue();
        int sum = 0;
        while (!master.isAllJobComplete()) {
            Object powerResult = results.poll();
            if (powerResult != null) {
                System.out.println(powerResult);
                sum += (Integer) powerResult;
            }
        }
        System.out.println("The power sum is " + sum);
    }
}
